package com.itheima.controller;

import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Menu;
import com.itheima.service.UserService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Reference
    private UserService userService;
    @RequestMapping("/getUsername")
    public Result getUsername(){

        //因为使用的是security框架,可以从上下文对象里面拿去对象
        User user= null;
        try {
            user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            String username = user.getUsername();
            ArrayList<Menu> menu=userService.getMenu(username);
            //通过username拿出来user
            String img=userService.getUserImg(username);
            Map<String,Object> map=new HashMap <>();
            map.put("username",username);
            map.put("img",img);
            map.put("data",menu);
            return new Result(true, MessageConstant.GET_USERNAME_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_USERNAME_FAIL);
        }
    }
    //拿取前端传过来的用户名,密码
    @RequestMapping("/updateUser")
    public Result updateUser(@RequestBody Map map){
        String user = (String) map.get("code");
        String passwordcode = (String) map.get("password");
        String imgSet = (String) map.get("imgSet");

        //把账号密码发给后端修改
        try {
            userService.change(user,passwordcode,imgSet);
            return new Result(true,MessageConstant.GET_USERNAME_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true,MessageConstant.GET_USERNAME_FAIL);
        }
    }
}
